<template>
  <div class="dynamic-table">

    <!-- :show-header="fromData.tableData.length > 0" -->
    <el-form :model="fromData" ref="ruleForm">
      <el-table :data="fromData.tableData" border size="small" class="table-box"
        empty-text="暂无数据"
        :span-method="cellMerge1"
        @selection-change="handleSelectionChange"
       :header-cell-style="tableHeaderColor">
       <el-table-column type="selection" width="55" v-if="!statics"></el-table-column>
        <el-table-column type="index" label="序号" v-if="statics" align="center"></el-table-column>
        <el-table-column label="用户" prop="owner" v-if="statics" align="center">
            <template slot-scope="scope">
                <span class="content">{{ scope.row.owner }}</span>
              </template>
        </el-table-column>
        <template v-for="item in tableHeader">
          <table-column v-if="item.child && item.child.length" :key="item.id" :coloumn-header="item" :isInput="isInput">
          </table-column>
          <el-table-column v-else :key="item.id" :label="item.name" :prop="item.prop" align="center" min-width="180">
            <template slot-scope="scope">
              <el-form-item v-if="isInput" :prop="'tableData.' + scope.$index + '.'+item.prop"
              :rules="item.status === '必填' ? fromaDataRules.name : {}">
              <el-input type="textarea" :rows="1" v-model="scope.row[item.prop]" size="small" style="width: 100%;border:none" class="inputClass">
                </el-input>
              </el-form-item>
              <span class="content" v-else>{{ scope.row[item.prop] }}</span>
            </template>
          </el-table-column>
        </template>
      </el-table>
    </el-form>
  </div>
</template>

<script>
  import TableColumn from './components/TableColum'
  import {
    postTableReport,
    postDelTableRecordByUuid
  } from '@/api/question'
  import {
    uuid
  } from '@/utils/index.js'
  export default {
    props: {
      // 表格的数据
      tableData: {
        type: Array,
        required: true
      },
      // 多级表头的数据
      tableHeader: {
        type: Array,
        required: true
      },
      // 表格的高度
      formId: {
        type: Number
      },
      isInput: {
        type: Boolean,
        default: true
      },
      statics:{
        type:Boolean,
        default: false
      },
      initUuidList:{
        type: Array
      }
    },
    components: {
      TableColumn
    },
    watch: {
      tableData(data){
        if(this.statics){
          this.getSpanArr(data)
        }
        this.fromData.tableData = data
      }
    },
    data() {
      return {
        fromData: {
          tableData: []
        },
        multipleSelection: [],
        fromaDataRules: {
          name: [{
            required: true,
            message: '\n',
            trigger: 'blur'
          }],
          desc: [{
            required: true,
            message: '\n',
            trigger: 'blur'
          }]
        },
        spanArr: [],
      pos: 0,
        // 修改table header的背景色
        tableHeaderColor({
          row,
          rowIndex
        }) {
          return 'background-color: #f5f5f5;color: #666;'
        },
      }
    },
    methods: {
       // 表格多选
       handleSelectionChange(val) {
          this.multipleSelection = val;
          this.$emit('selectedData', val)
        },
      submit(flag) {
        this.$refs['ruleForm'].validate((valid) => {
          if (valid) {
            this.putTableForm(flag)
          } else {
            this.$message.warning('必填项不能为空，请输入内容！')
            return false;
          }
        });
      },
      // 将填报表格数据转换
      formatPostData(data){
        const param = {
          form: this.formId,
          data: []
        }
        data.forEach(e =>{
          let record = Object.keys(e).map(key =>{
              return {
                content: e[key],
                id: key
              }
          })
          param.data.push({
            uuid: uuid(),
            item: record
          })
        })
        return param
      },
      putTableForm(flag) {
        const param = this.formatPostData(this.tableData)
        const superior =  flag ? 'True' : 'False'
        param['not_view'] = superior
        const uuidList = []
        // 处理uuid两边双引号
        this.initUuidList.forEach(e =>{
          uuidList.push(e.replace("\"","").replace("\"",""))
        })
        postTableReport(param).then(res => {
            if(res && res.data){
              this.$message.success('数据填报成功');
              postDelTableRecordByUuid({ uuid: uuidList}).then(
                res =>{
                  if(res && res.data){
                    this.$emit('reloadReport')
                  }
                }
            )
            }
          })
          .catch(err =>{
            this.$message.error('错了哦，数据填报失败');
          })
      },
      transformTable(data) {
        const param = []
        // const data = this.tableData[0]
        Object.keys(data).forEach(e => {
          if (e.includes('p_content')) {
            param.push(e)
          }
        })
        const list = []
        param.forEach(item => {
          let id = item.split('p_content')[1]
          const obj = {
            id: id,
            p_content: data[item],
            child: []
          }
          Object.keys(data).forEach(e => {
            if (e.includes(id + 'c_content')) {
              let arr = e.split('c_content')
              obj.child.push({
                id: arr[1],
                c_contnet: data[e]
              })
            }
          })
          list.push(obj)
        })
        return list
        // data.forEach(item=>{

        // })
      },
      getSpanArr(data) {　
  for (var i = 0; i < data.length; i++) {
        if (i === 0) {
              this.spanArr.push(1);
              this.pos = 0
        } else {
          // 判断当前元素与上一个元素是否相同
    if (data[i].owner === data[i - 1].owner) {
                this.spanArr[this.pos] += 1;
                this.spanArr.push(0);
              } else {
                this.spanArr.push(1);
                this.pos = i;
              }
        }
    }
},
    cellMerge1({ row, column, rowIndex, columnIndex }) {
      if(!this.statics) return
      if (columnIndex === 1) {
            const _row = this.spanArr[rowIndex];
            const _col = _row > 0 ? 1 : 0;
            return {
                  rowspan: _row,
                  colspan: _col
            }
      }
},
    },
  }

</script>

<style lang="scss">
  .dynamic-table {
    .content{
      /* text-align: left; */
      height: 30px;
      /* margin-left: 10px; */
      display: inline-block;
      width: 100%;
      font-size: 14px;
      line-height: 30px;
    }
    
  }

</style>
